# encoding: utf-8
import numpy
import math
import sys, os
import logging
import platform
import pyomo.environ as pyomo

def isWindowsSystem():
    return 'Windows' in platform.system()

def isLinuxSystem():
    return 'Linux' in platform.system()

class lp_solve(object):
    def __init__(self):

        self.initialize_solver()

    def initialize_solver(self):
        ### Create the ipopt solver plugin using the ASL interface
        solver = 'ipopt'#'cbc'#'ipopt'
        solver_io = 'nl'
        if isLinuxSystem():
            #ipopt_path = os.path.join('/usr/bin/', "cbc")
           # ipopt_path = os.path.join('/home/MicroService/ControlService/bin/Ipopt/', "ipopt")
            ipopt_path = os.path.join('/home/MicroService/ControlService/bin/Test2/bin/',"ipopt")
        elif isWindowsSystem():
            #ipopt_path = os.path.join(self.settings.ROOT_DIR, "bin/ipopt.exe")
            ipopt_path = os.path.join('C:/ENERMOD/Ipopt/', "ipopt.exe")
        else :
            print ("UNKNOW SYSTEM")
            exit(1)
        self.opt = pyomo.SolverFactory(solver, solver_io=solver_io, executable=ipopt_path,
                                           logging='quiet')
        #self.opt.options["print_level"] = 0
        #self.opt.options['suppress_all_output'] = "yes"
        #self.opt = pyomo.SolverFactory("cbc")
                
        if self.opt is None:
            print("")
            print("ERROR: Unable to create solver plugin for %s "\
                  "using the %s interface" % (solver, solver_io))
            print("")
            exit(1)

    def set_objective_rule(self, optimization_objective):
        self.optimization_objective = optimization_objective

    def run(self, model):

        logging.getLogger('pyomo').setLevel(logging.ERROR)

        stream_solver = True  # True prints solver output to screen
        keepfiles = False  # True prints intermediate file names (.nl,.sol,...)

        '''
        for n in range(1,15):
            def minUsePre_rule(m, u, v):
                return sum(m.X[u, v] for (u, v) in bay_setPre[n]) == 1.0

            setattr(m, "minUsePre" + n, pe.Constraint(m.arc_set, rule=minUsePre_rule))
            '''
        ###
        results = self.opt.solve(model, keepfiles=keepfiles, tee=stream_solver)

        model.solutions.load_from(results)

        x = [0] * len(model.s)

        for i in range(0, len(model.s)):
            x[i] = model.x[i].value

        return x
